<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>华北水利在线学习</title>
</head>
<script src="/webjars/jquery/3.0.0/jquery.min.js"></script>
<script src="/webjars/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="/js/jquery.cookie.min.js"></script>
<link href="/webjars/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script>
  var socket;

  /**
   * jquery的初始化
   **/
  $(document).ready(function () {
    //初始化
    connected();
  });

  /**
   *建立连接
   *
   **/
  function openSocket(clientCode) {
    if (typeof (WebSocket) == "undefined") {
      alert("您的浏览器不支持WebSocket");
    } else {
      //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
      //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
      let baseSocketUrl = $("#socketUrlId").val();
      var socketUrl = baseSocketUrl + "/hbsl/" + clientCode;
      socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
      if (socket != null) {
        socket.close();
        socket = null;
      }

      socket = new WebSocket(socketUrl);
      $("#onlineimg").attr("src", '/images/online/online.png');
      $("#onlinespan").text("在线[" + clientCode + "]");

      //打开事件[websocket已打开][socket.send("这是来自客户端的消息" + location.href + new Date());]
      socket.onopen = function () {

      };
      //获得消息事件
      socket.onmessage = function (msg) {
        let data = JSON.parse(msg.data);
        var idinfo = "";
        if (data.type == 2) {
          idinfo = "#divCenterTextarea";
        } else if (data.type == 3) {
          idinfo = "#divRightTextarea";
        } else {
          idinfo = "#divLeftTextarea";
        }
        if (idinfo) {
          $(idinfo).append(data.msg + "\n");
          $(idinfo).scrollTop($(idinfo)[0].scrollHeight);
        }
      };
      //关闭事件
      socket.onclose = function () {
        console.log("websocket已关闭");
      };
      //发生了错误事件
      socket.onerror = function () {
        console.log("websocket发生了错误");
      }
    }
  }

  /**
   * 发送消息
   */
  function sendMessage() {
    if (typeof (WebSocket) == "undefined") {
      alert("您的浏览器不支持WebSocket");
    } else {
      console.log('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
      socket.send('{"toUserId":"' + $("#toUserId").val() + '","contentText":"' + $("#contentText").val() + '"}');
    }
  }

  /**
   * 生成客户端id
   */
  function generatorClientId(isConnected) {
    var cookieKey = 'hbsl';
    let cookie = $.cookie(cookieKey);

    if (cookie && isConnected) {
      $("#onlineimg").attr("src", '/images/online/online.png');
      $("#onlinespan").text("在线[" + cookie + "]");
    } else {
      $("#onlineimg").attr("src", '/images/online/unonline.png');
      $("#onlinespan").text("离线重连");
      var clientCode = cookie;
      if (!clientCode) {
        clientCode = ('000000' + Math.floor(Math.random() * 999999)).slice(-6);
      }

      $.cookie(cookieKey, clientCode, {expires: 30});
      //连接事件
      this.openSocket(clientCode);
    }
  }

  /**
   * 开始学习
   */
  function submitCommand() {
    var classcode = $("#classcode").val();
    var classdesc = $("#classdesc").val();
    if (!classcode) {
      alert("请输入正确的课程码");
      return;
    }
    $.ajax({
      type: "POST",    //请求类型
      url: "/hbsl/addClass",
      data: JSON.stringify({"body": {"classcode": classcode, "classdesc": classdesc}}),
      contentType: "application/json",
      dataType: "json",
      success: function (res) {
        if (res.body) {
          $("#divLeftTextarea").append("添加学习码[" + classcode + "]学习教程[" + classdesc + "]成功\n\n");
          $("#divLeftTextarea").scrollTop($("#divLeftTextarea")[0].scrollHeight);
        } else {
          $("#divLeftTextarea").append("添加学习码[" + classcode + "]学习教程[" + classdesc + "]失败\n\n");
          $("#divLeftTextarea").scrollTop($("#divLeftTextarea")[0].scrollHeight);
        }
      },
      error: function (msg) {
        alert("添加关键词失败");
      }
    });
  }

  /**
   *正在学习
   **/
  function studying() {
    $.ajax({
      type: "POST",    //请求类型
      url: "/hbsl/studying",
      contentType: "application/json",
      dataType: "json",
      success: function (res) {
        $("#divLeftTextarea").append(new Date() + "\n正在学习的信息:" + JSON.stringify(res.body) + "\n\n");
        $("#divLeftTextarea").scrollTop($("#divLeftTextarea")[0].scrollHeight);
      },
      error: function (msg) {
        alert("添加关键词失败");
      }
    });
  }

  /**
   * 触发学习
   **/
  function triggerStudy() {
    $.ajax({
      type: "POST",    //请求类型
      url: "/hbsl/triggerStudy",
      contentType: "application/json",
      dataType: "json",
      success: function (res) {
        $("#divLeftTextarea").append("所有课程正在飞速学习中\n\n");
        $("#divLeftTextarea").scrollTop($("#divLeftTextarea")[0].scrollHeight);
      }
    });
  }

  /**
   * 放弃学习
   **/
  function giveUpStudy() {
    $.ajax({
      type: "POST",    //请求类型
      url: "/hbsl/giveUpStudy",
      contentType: "application/json",
      dataType: "json",
      success: function (res) {
        $("#divLeftTextarea").append("所有课程正在都已经停止学习了哦\n\n");
        $("#divLeftTextarea").scrollTop($("#divLeftTextarea")[0].scrollHeight);
      }
    });
  }

  /**
   * 加载学习
   **/
  function loadStudy() {
    $.ajax({
      type: "POST",    //请求类型
      url: "/hbsl/loadStudy",
      contentType: "application/json",
      dataType: "json",
      success: function (res) {
        //学习的信息
        studying();

        $("#divLeftTextarea").append("正在加载学习\n\n");
        $("#divLeftTextarea").scrollTop($("#divLeftTextarea")[0].scrollHeight);
      }
    });
  }

  function submitCookie() {
    var cookie = $("#cookie").val();
    var studynum = $("#studynum").val();
    if (!classcode) {
      alert("请输入正确的cookie");
      return;
    }
    $.ajax({
      type: "POST",    //请求类型
      url: "/hbsl/updateStudyParam",
      data: JSON.stringify({"body": {"cookie": cookie, "studyNum": studynum}}),
      contentType: "application/json",
      dataType: "json",
      success: function (res) {
      },
      error: function (msg) {
        alert("添加关键词失败");
      }
    });
  }

  /**
   * 验证是否已经连接状态
   */
  function connected() {
    var cookieKey = 'hbsl';
    let clientCode = $.cookie(cookieKey);
    if (!clientCode) {
      generatorClientId(false);
      return;
    }
    $.ajax({
      type: "POST",    //请求类型
      url: "/hbsl/connected",
      data: JSON.stringify({"body": {"clientCode": clientCode}}),
      contentType: "application/json;charset=UTF-8",
      dataType: "json",
      success: function (res) {
        generatorClientId(res.body);
      },
      error: function (msg) {
        alert("添加关键词失败");
      }
    });
  }

  /**
   * 清除日志
   */
  function cleanArea() {
    $("#divCenterTextarea").text('');
    $("#divRightTextarea").text('');
    $("#divLeftTextarea").text('');
  }


</script>
<body>

<input type="hidden" id="socketUrlId" value='${socketUrl}'/>

<!--在线显示状态-->
<div style="height: 100px">
  <button onclick="connected()">开启检测</button>
  <button onclick="cleanArea()">清理日志</button>
  <div id="cookieForm">
    <input id="cookie" placeholder="学习cookie" type="text"/>
    <input id="studynum" placeholder="学习次数" value="10" type="text"/>
    <button onclick="submitCookie()" type="button">更新cookie</button>
  </div>
  <div id="classForm">
    <input id="classcode" placeholder="课程唯一码" type="text"/>
    <input id="classdesc" placeholder="课程描述" type="text"/>
    <button onclick="submitCommand()" type="button">开始学习</button>
    <button onclick="studying()" type="button">正在学习</button>
    <button onclick="triggerStudy()" type="button">主动学习</button>
    <button onclick="giveUpStudy()" type="button">放弃学习</button>
    <button onclick="loadStudy()" type="button">加载学习</button>
  </div>
  <span id="onlinespan" style="line-height:60px;position: absolute;right: 100px;top: 30px;">
    在线
  </span>
  <img id="onlineimg" onclick="javascript:location.href='/'" src="/images/online/online.png"
       style="line-height:60px; position: absolute;right: 30px;top: 30px;height: 60px;width: 60px;"/>
</div>

<div id="divLeft">
  <div id="divLeftSpan" style="text-align: center;">操作事件</div>
  <textarea id="divLeftTextarea" readonly style="width: 100%;height: 100%"></textarea>
</div>

<div id="divRight">
  <div id="divRightSpan" style="text-align: center;">实时日志</div>
  <textarea id="divRightTextarea" readonly style="width: 100%;height: 100%"></textarea>
</div>

<div id="divCenter">
  <div id="divCenterSpan" style="text-align: center;">学习日志</div>
  <textarea id="divCenterTextarea" readonly style="height: 100%;width: 40%;"></textarea>
</div>


</body>
</html>
<style type="text/css">
  body {
    margin: 0px;
  }

  #divLeft {
    width: 30%;
    height: 600px;
    float: left;
    border: 1px solid black;
  }

  #divCenter {
    width: 100%;
    height: 600px;
    border: 1px solid black;
  }

  #divRight {
    width: 30%;
    height: 600px;
    float: right;
    border: 1px solid black;
  }

</style>

